//
//  AppDelegate.swift
//  WeiboSwift
//
//  Created by hfwd on 2017/5/8.
//  Copyright © 2017年 hfwd. All rights reserved.
//

import UIKit
import UserNotifications
import SVProgressHUD
import AFNetworking

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        //设置应用程序额外信息
        setupAdditions()
    
        window = UIWindow()
        
        window?.backgroundColor = UIColor.white
        
        window?.makeKeyAndVisible()
        
        //设置根视图控制器
        window?.rootViewController = WBTabBarViewController()
        
        //将Bundle中的json文件中的tabbar的数据，以及访客视图的数据写入沙盒
        loadAppInfo()
        
        return true
    }
}

// MARK: - 设置应用程序额外信息
extension  AppDelegate {
    
    fileprivate func setupAdditions() {
        
        SVProgressHUD.setMinimumDismissTimeInterval(1)
        
        AFNetworkActivityIndicatorManager.shared().isEnabled = true
        
        //注册系统通知
        registerNotification()
    }
    
}

// MARK: - 从服务器上加载应用程序信息
extension AppDelegate {
    
    /// 将Bundle中的json文件中的tabbar的数据，以及访客视图的数据写入沙盒
    fileprivate func loadAppInfo() {
        
        DispatchQueue.global().async {
            
            let url = Bundle.main.url(forResource: "main.json", withExtension: nil)
            
            let data = NSData(contentsOf: url!)
            
            var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            path.append("/main.json")
            
            data?.write(toFile: path, atomically: true)
        }
    }
}

// MARK: - 注册系统通知
extension AppDelegate {
    
    fileprivate func registerNotification() {
        
        if #available(iOS 10.0, *) {
            
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound, .carPlay], completionHandler: { (success, error) in
                
                print(error ?? "授权成功")
            })
            
        } else {
            
            let notifySettings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
            
            UIApplication.shared.registerUserNotificationSettings(notifySettings)
        }
    }
}


